import pygame,sys
import  random,time


_display = pygame.display
color_black = pygame.Color(0, 0, 0)
color_red = (0, 255, 0)


# 游戏主主窗口
class MainGame():
    window=None
    screen_height=500
    screen_width=800
    TANK_P1 = None
    EnemyTank_list = []
    EnemTank_count = 5
    Bullet_list = []
    Enemy_bullet_list=[]
    Explode_list=[]
    Wall_list=[]


    def __init__(self):
        pass

    def blitWalls(self):
        for wall in MainGame.Wall_list:
            if wall.live:
                wall.displayWall()

            else:
                MainGame.Wall_list.remove(wall)


    def creatWalls(self):
        for i in range(6):
            wall = Wall(130 * i, 240)
            MainGame.Wall_list.append(wall)


    def blitEnemyBullet(self):
        for eBullet in MainGame.Enemy_bullet_list:
            if eBullet.live:
                eBullet.displayBullet()
                eBullet.bulletMove()


                if MainGame.TANK_P1 and MainGame.TANK_P1.live:
                    eBullet.hitMyTank()
            else:
                MainGame.Enemy_bullet_list.remove(eBullet)

    def displayExplodes(self):
        for explode in MainGame.Explode_list:
            if explode.live:
                explode.displayExplode()
            else:
                MainGame.Explode_list.remove(explode)



    def blitBullet(self):
        for bullet in MainGame.Bullet_list:
            if bullet.live:
                bullet.displayBullet()
                bullet.bulletMove()
                bullet.hitEnemyTank()
                bullet.hitWalls()
            else:
                MainGame.Bullet_list.remove(bullet)

    def getEvent(self):
        eventList = pygame.event.get()
        for event in eventList:
            if event.type == pygame.QUIT:
                self.endGame()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    MainGame.TANK_P1.direction = 'L'
                    MainGame.TANK_P1.stop = False
                elif event.key == pygame.K_RIGHT:
                    MainGame.TANK_P1.direction = 'R'
                    MainGame.TANK_P1.stop = False
                elif event.key == pygame.K_UP:
                    MainGame.TANK_P1.direction = 'U'
                    MainGame.TANK_P1.stop = False
                elif event.key == pygame.K_DOWN:
                    MainGame.TANK_P1.direction = 'D'
                    MainGame.TANK_P1.stop = False
                elif event.key == pygame.K_SPACE:
                    print("发射子弹")
                    # 产生一颗子弹
                    m = Bullet(MainGame.TANK_P1)
                    # 将子弹加入到子弹列表
                    MainGame.Bullet_list.append(m)
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    MainGame.TANK_P1.stop = True


    def getTextSurface(self, text):
        pygame.font.init()
        font = pygame.font.SysFont("kaiti", 18)
        textSurface = font.render(text, True, color_red)
        return textSurface


    def createEnemyTank(self):
        top=100
        speed=random.randint(3,6)
        for i in range(MainGame.EnemTank_count):
            left=random.randint(1,7)
            eTank=EnemyTank(left*100,top,speed)
            MainGame.EnemyTank_list.append(eTank)
            # print(eTank)

    def blitEnemyTank(self):
        for eTank in MainGame.EnemyTank_list:
            if eTank.live:
                eTank.displayTank()
                eTank.randMove()
                eBullet = eTank.shot()



                # 如果子弹为 None。不加入到列表
                if eBullet:
                    # 将子弹存储敌方子弹列表
                    MainGame.Enemy_bullet_list.append(eBullet)

            else:
                MainGame.EnemyTank_list.remove(eTank)


    def endGame(self):
        print("谢谢使用")
        exit()




    def startGame(self):
        pygame.init()
        MainGame.window= _display.set_mode([MainGame.screen_width,MainGame.screen_height])
        MainGame.TANK_P1 = Tank(400, 300)
        _display.set_caption("坦克大战")
        self.createEnemyTank()




        while True:

            MainGame.window.fill(color_black)
            self.getEvent()

            MainGame.window.blit(self.getTextSurface("剩余敌方坦克%d" % 5), (5, 5))
            # 展示我方坦克



            if MainGame.TANK_P1 and not MainGame.TANK_P1.stop:
                MainGame.TANK_P1.move()
                MainGame.TANK_P1.hitEnemyTank( )
                MainGame.TANK_P1.hitWalls()
                # if MainGame.TANK_P1.live==False:
                #     self.endGame()



            # 循环展示第方坦克
            time.sleep(0.03)

            self.blitEnemyTank()
            self.blitBullet()
            self.blitEnemyBullet()
            self.displayExplodes()
            self.creatWalls()
            self.blitWalls()
            MainGame.TANK_P1.displayTank()





            _display.update()
# --------------------------------------------------------------------------
class BaseItem(pygame.sprite.Sprite):
    def __init__ (self):
        pygame.sprite.Sprite.__init__(self)




# ------------------------------------------------------------------------------
class Tank(BaseItem):
    def __init__(self,left,top):
        self.images={
            'U':pygame.image.load('D:\pythonwork\img\img\p1tankU.gif'),
            'D': pygame.image.load('D:\pythonwork\img\img\p1tankD.gif'),
            'L': pygame.image.load('D:\pythonwork\img\img\p1tankL.gif'),
            'R': pygame.image.load('D:\pythonwork\img\img\p1tankR.gif')

        }
        self.direction='U'
        self.image=self.images[self.direction]
        # 坦克所在区域
        self.rect=self.image.get_rect()
        # 指定坦克初始化位置
        self.rect.left=left
        self.rect.top=top
        self.speed=5
        self.stop=True
        self.live=True
        self.oldLeft=self.rect.left
        self.oldTop= self.rect.top

    def displayTank(self):
        # 1.重新设置坦克的图片
        self.image=self.images[self.direction]
        # 将坦克加入到窗口中
        MainGame.window.blit(self.image,self.rect)




    # 坦克移动
    def move(self):
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top
        if self.direction=='L':
                if self.rect.left>0:
                    self.rect.left-=self.speed


        elif self.direction=='R':
            if self.rect.left+self.rect.height<MainGame.screen_width:
                self.rect.left+=self.speed


        elif self.direction=='U':
            if self.rect.top>0:
                self.rect.top-=self.speed


        elif self.direction=='D':
            if self.rect.top+self.rect.height<MainGame.screen_height:
                self.rect.top+=self.speed



    def hitEnemyTank(self):
        for eTank in MainGame.EnemyTank_list:
            if pygame.sprite.collide_rect(eTank, self):
                explode = Explode(eTank)
                MainGame.Explode_list.append(explode)
                self.live = False
                eTank.live = False

    def stay(self):
        self.rect.left = self.oldLeft
        self.rect.top = self.oldTop


    # 新增碰撞墙壁的方法
    def hitWalls(self):
        for wall in MainGame.Wall_list:
            if pygame.sprite.collide_rect(wall, self):
                self.stay()


#-----------------------------------------------------------------------------------
# ------------------------------------------------------------------------
class EnemyTank(Tank):
    def __init__(self,left,top,speed):
        self.images={
            'U':pygame.image.load('D:\pythonwork\img\img\enemy1U.gif'),
            'D': pygame.image.load('D:\pythonwork\img\img\enemy1D.gif'),
            'L': pygame.image.load('D:\pythonwork\img\img\enemy1L.gif'),
            'R': pygame.image.load('D:\pythonwork\img\img\enemy1R.gif')
        }
        self.direction=self.randDirection()
        self.image=self.images[self.direction]
        self.step=1

        # 坦克所在区域
        self.rect=self.image.get_rect()
        # 指定坦克初始化位置
        self.rect.left=left
        self.rect.top=top
        # 新增加速度属性
        self.speed=speed
        self.stop=True
        self.live=True

    def randDirection(self):
        num = random.randint(1, 4)
        if num == 1:
            return 'U'
        elif num == 2:
            return 'D'
        elif num == 3:
            return 'L'
        elif num == 4:
            return 'R'


    #实现随机移动
    def randMove(self):
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top
        if self.step <= 0:
            self.direction = self.randDirection()
            self.step = 50
        else:
            self.move()
            self.hitWalls()
            self.step -= 1

    def shot(self):
        num = random.randint(1, 1000)
        if num <= 20:
            return Bullet(self)



#------------------------------------------------------------------------------------
class Bullet(BaseItem):
    def __init__(self,Tank):
        self.image = pygame.image.load('D:\pythonwork\img\img\enemymissile.gif')
        self.direction = Tank.direction
        self.rect = self.image.get_rect()
        if self.direction == 'U':
            self.rect.left = Tank.rect.left + Tank.rect.width / 2 - self.rect.width / 2
            self.rect.top = Tank.rect.top - self.rect.height
        elif self.direction == 'D':
            self.rect.left = Tank.rect.left + Tank.rect.width / 2 - self.rect.width / 2
            self.rect.top = Tank.rect.top + Tank.rect.height
        elif self.direction == 'L':
            self.rect.left = Tank.rect.left - self.rect.width / 2 - self.rect.width / 2
            self.rect.top = Tank.rect.top + Tank.rect.width / 2 - self.rect.width/2
        elif self.direction == 'R':
            self.rect.left = Tank.rect.left + Tank.rect.width
            self.rect.top = Tank.rect.top + Tank.rect.width / 2 - self.rect.width / 2

        self.speed = 7

        self.live = True

#     子弹移动方向
    def bulletMove(self):
        if self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
            else:
                self.live = False
        elif self.direction == 'D':
            if self.rect.top < MainGame.screen_width - self.rect.height:
                self.rect.top += self.speed
            else:
                self.live = False
        elif self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
            else:
                self.live = False
        elif self.direction == 'R':
            if self.rect.left < MainGame.screen_width - self.rect.width:
                self.rect.left += self.speed
            else:
                self.live = False
#     展示子弹
    def displayBullet(self):
        MainGame.window.blit(self.image,self.rect)
#     我方子弹碰撞敌方坦克方法
    def hitEnemyTank(self):
        for eTank in MainGame.EnemyTank_list:
            if pygame.sprite.collide_rect(eTank, self):
                explode = Explode(eTank)
                MainGame.Explode_list.append(explode)
                self.live = False
                eTank.live = False

    def hitMyTank(self):
        if pygame.sprite.collide_rect(self, MainGame.TANK_P1):
            explode = Explode(MainGame.TANK_P1)
            MainGame.Explode_list.append(explode)
            self.live = False
            MainGame.TANK_P1.live = False

#子弹与墙壁的碰撞
    def hitWalls(self):
        for wall in MainGame.Wall_list:
            if pygame.sprite.collide_rect(wall, self):
                self.live = False
                wall.hp -= 1
                if wall.hp <= 0:
                    wall.live = False


# -----------------------------------------------------------------------
class Explode():
    def __init__(self,tank):
        self.rect = tank.rect
        self.step = 0
        self.images = [
            pygame.image.load('D:\pythonwork\img\img\\blast0.gif'),
            pygame.image.load('D:\pythonwork\img\img\\blast1.gif'),
            pygame.image.load('D:\pythonwork\img\img\\blast2.gif'),
            pygame.image.load('D:\pythonwork\img\img\\blast3.gif'),
            pygame.image.load('D:\pythonwork\img\img\\blast4.gif')
        ]
        self.image = self.images[self.step]
        self.live = True

    def displayExplode(self):
        if self.step < len(self.images):
            MainGame.window.blit(self.image, self.rect)
            self.image = self.images[self.step]
            self.step += 1
        else:
            self.live = False
            self.step = 0

# -----------------------------------------------------------------
class Wall():
    def __init__(self,left,top):
        self.image = pygame.image.load('D:\pythonwork\img\img\\steels.gif')
        self.rect = self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        # 用来判断墙壁是否应该在窗口中展示
        self.live = True
        # 用来记录墙壁的生命值
        self.hp = 3
    # 展示墙壁的方法
    def displayWall(self):
        MainGame.window.blit(self.image,self.rect)




# TEST
MainGame().startGame()

